package repository

import (
	"fmt"
	"hcy-api/structs/idp"
	"hcy-api/structs/tables"
	"idp/global"
	"time"
)

var TaskRepository = new(taskRepository)

type taskRepository struct {
}

func (r taskRepository) FindTaskById(taskId int64) (m tables.IdpTask, err error) {
	err = global.DB.Model(&tables.IdpTask{}).Where(&tables.IdpTask{Id: taskId}).Find(&m).Error
	return
}

// FindAll 查询所有未过期的任务
func (r taskRepository) FindAll() (li []tables.IdpTask, err error) {
	err = global.DB.Model(&tables.IdpTask{}).Where("end_time >= ? and status = ?", time.Now().Unix(), tables.IdpTaskStatusForNormal).Find(&li).Error
	return
}

func (r taskRepository) FindPage(in idp.SearchTaskDto) (li []tables.IdpTask, total int64, err error) {
	err = global.DB.Model(&tables.IdpTask{}).Where("name like ?", fmt.Sprintf("%%%s%%", in.Name)).
		Order("created_at desc").Count(&total).Limit(in.PageSize).Offset((in.PageNum - 1) * in.PageSize).
		Find(&li).Error
	return
}

// UpdateTaskExpiredById 更新任务状态为过期，过期分为自动过期和管理员干预过期两种
func (r taskRepository) UpdateTaskExpiredById(taskId int64, status int8) (err error) {
	err = global.DB.Exec("update idp_task set status = ? where id = ?", status, taskId).Error
	return
}

// UpdateTaskExpired 将超过时效的任务标记为自动过期
func (r taskRepository) UpdateTaskExpired() (err error) {
	err = global.DB.Exec("update idp_task set status = ? where end_time <= ?", tables.IdpTaskStatusForExpired, time.Now().Unix()).Error
	return
}

// FindTaskResult 查询任务结果
func (r taskRepository) FindTaskResult(taskId, clientId int64) (li []tables.IdpTaskResult, err error) {
	err = global.DB.Raw("select * from idp_task_result_log where task_id=? and client_id=? order by  created_at desc", taskId, clientId).Find(&li).Error
	return
}

// FindTaskResultIsOk 查看是否存在已经ok的结果
func (r taskRepository) FindTaskResultIsOk(taskId, clientId int64) (ok bool, err error) {
	var num int64
	err = global.DB.Raw("select count(*) from idp_task_result_log where task_id=? and client_id=? and is_ok = ?", taskId, clientId, tables.IdpTaskResultForOk).Find(&num).Error
	ok = num > 0
	return
}

func (r taskRepository) CreateTaskResult(m *tables.IdpTaskResult) (err error) {
	return global.DB.Create(m).Error
}

func (r taskRepository) CreateTask(m *tables.IdpTask) (err error) {
	err = global.DB.Create(m).Error
	return
}

// CountTaskReportNum 统计多少设备上报过信息
func (r taskRepository) CountTaskReportNum(taskId int64) (num int64, err error) {
	err = global.DB.Raw("select count(distinct (client_id)) from idp_task_result_log where task_id =?", taskId).Scan(&num).Error
	return
}

// CountTaskOkNum 统计任务有多少设备上报过OK类消息
func (r taskRepository) CountTaskOkNum(taskId int64) (num int64, err error) {
	err = global.DB.Raw("select count(distinct (client_id)) from idp_task_result_log where task_id =? and is_ok =?", taskId, tables.IdpTaskResultForOk).Scan(&num).Error
	return
}
